<template>
  <div id="sales-all-order">
    <div class="search-box">
        <el-form>
             <el-form-item label="店铺名称：">
                <el-select v-model="searchForm.shopId" placeholder="请选择店铺" size="small" filterable :filter-method="dataFilter" clearable>
                  <el-option v-for="(item, index) in shopNameList" :key="index" :label="item.name" :value="item.id"></el-option>
                </el-select>
             </el-form-item>

             <el-form-item label="计划ID：">
               <el-input placeholder="请输入计划ID" v-model="searchForm.planCode" size="small" clearable></el-input>
             </el-form-item>
             <el-form-item label="任务ID：">
               <el-input placeholder="请输入任务ID" v-model="searchForm.taskCode" size="small" clearable></el-input>
             </el-form-item>
             <el-form-item label="商品ID：">
               <el-input placeholder="请输入商品ID" v-model="searchForm.productId" size="small" clearable></el-input>
             </el-form-item>
             <el-form-item label="任务状态 ：">
               <el-select v-model="searchForm.taskStatus" placeholder="请选择任务状态" size="small">
                 <el-option label="全部" value=""></el-option>
                 <el-option v-for="(item, index) in taskStatusData" :key="index" :label="item.label" :value="item.value"></el-option>
               </el-select>
             </el-form-item>
             <el-form-item label="任务开始时间 ：">
              <el-date-picker format="yyyy-MM-dd HH:mm:ss" value-format="timestamp" size="small" v-model="searchTime"  @change="changeTime" type="datetimerange" range-separator="至" start-placeholder="开始日期" end-placeholder="结束日期" :picker-options="pickerOptions" :default-time="['00:00:00', '23:59:59']" ></el-date-picker>
             </el-form-item>
            <el-form-item>
                <el-button class="search-btn" icon="el-icon-ali-search" @click="searchData">查&nbsp;询</el-button>
            </el-form-item>
            <el-form-item>
                <el-button class="reset-btn" icon="el-icon-ali-reset" @click="resetSearchParam">重&nbsp;置</el-button>
            </el-form-item>
        </el-form>
    </div>
    <div class="table-box">
      <el-table border :data="tableData" max-height="580px">
        <el-table-column prop="platform_type" label="店铺类型/店铺名称">
          <div slot-scope="scope">
           <div class="textColor">{{getShopType(scope.row)}}</div>
           <div>{{scope.row.shop_name}}</div>
          </div>
        </el-table-column>
        <el-table-column width="120px" prop="goods_img" label="商品主图">
          <el-popover placement="right" trigger="hover" slot-scope="scope" v-if="scope.row.goods_img">
            <img class="goods-preview-img" :src="scope.row.goods_img"/>
            <img slot="reference" :src="scope.row.goods_img"  style="width: 80px;height: 80px">
          </el-popover>
        </el-table-column>
        <el-table-column prop="product_id" label="商品ID"></el-table-column>
        <el-table-column prop="status_name" label="任务状态" ></el-table-column>
        <el-table-column prop="keyword" label="关键词">
          <el-popover placement="right" trigger="hover" slot-scope="scope" v-if="scope.row.entrance_type == 3">
            <img class="keyword-preview-img" :src="scope.row.keyword"/>
            <img slot="reference" :src="scope.row.keyword"  style="width: 80px;height: 80px">
          </el-popover>
          <div v-else>
            {{scope.row.keyword}}
          </div>
        </el-table-column>
        <el-table-column prop="tb_name" label="推手账号" ></el-table-column>
        <el-table-column prop="plan_code" label="计划ID/任务ID">
          <div slot-scope="scope">
             <div class="planCodeStyle" @click="toPlanDetailPage(scope.row.plan_id, scope.row)">{{scope.row.plan_code}}</div>
             <div>{{scope.row.task_code}}</div>
          </div>
        </el-table-column>
        <el-table-column prop="begin_time" label="开始时间" :formatter="changeStartTimeType"></el-table-column>
        <el-table-column prop="over_time" label="结束时间" :formatter="changeOverTimeType"></el-table-column>
        <el-table-column prop="flag_status" label="标旗情况">
          <div slot-scope="scope">
            <div style="color: #ee7b5a;">{{ scope.row.flag_status == 1 ? "是" : "否" }}</div>
          </div>
        </el-table-column>
      </el-table>

      <el-table :data="allTableData" id="exportTable"   border v-show="false">
       <el-table-column prop="platform_type" label="店铺类型" :formatter="getShopType"></el-table-column>
       <el-table-column prop="shop_name" label="店铺名称"></el-table-column>
       <el-table-column prop="product_id" label="商品ID"></el-table-column>
       <el-table-column prop="plan_code" label="计划ID"></el-table-column>
       <el-table-column prop="task_code" label="任务ID"></el-table-column>
        <el-table-column prop="push_task_order_num" label="订单号"></el-table-column>
        <el-table-column prop="push_phone" label="推手账号"></el-table-column>
        <el-table-column prop="push_task_pay_money" label="付款金额"></el-table-column>
       <el-table-column prop="tb_name" label="接单账号"></el-table-column>
       <el-table-column prop="keyword" label="关键词"></el-table-column>
       <el-table-column prop="status_name" label="任务状态"></el-table-column>
       <el-table-column prop="keyword" label="关键词"></el-table-column>
       <el-table-column prop="begin_time" label="任务开始时间" :formatter="changeStartTimeType"></el-table-column>
       <el-table-column prop="begin_time" label="任务结束时间" :formatter="changeOverTimeType"></el-table-column>

      </el-table>
      <div class="table-footer">
        <div class="btn">
          <el-button icon="el-icon-download" class="download-btn" @click="downloadExcel">导出</el-button>
          <el-button icon="el-icon-download" class="download-btn" @click="exportSaleTaskAllList">优化导出</el-button>
        </div>
        <el-pagination :page-sizes="[5, 10, 15, 20]" :page-size="searchForm.pageSize" :current-page="searchForm.page" layout="total, sizes, prev, pager, next, jumper"
          :total="pageToatal" @size-change="handleSizeChange" @current-change="handleCurrentChange"></el-pagination>
      </div>
    </div>
  </div>
</template>

<script>
import {
  apiExportSaleTaskAllList,
  apiGetMerchantShopList,
  apiSaleTaskAllList
} from '../../request/api.js'
  import { mapGetters,mapActions } from 'vuex';
  export default{
    data(){
      return {
        searchForm:{
          token: '',
          page: 1,
          pageSize: 10,
          shopId: '',
          productId: '',
          planCode: '',
          taskCode: '',
          startTime: '',
          endTime: '',
          shopType: ''
        },
        searchTime: [],
        shopNameList: [],
        shopNameOptions: [],
        platformNameObject:{
          1: '淘宝',
          2: '天猫',
          3: '京东',
		  4: '1688',
          13: '唯品会',
          15: '拼多多'
        },
        entranceType: {
          1: '关键词',
          2: '淘口令',
          3: '二维码',
          4: '直播',
          5: '其他'
        },
        pageToatal: 0,
        tableData: [],
        pickerOptions: {
          disabledDate(time) {
             let merchantTime = window.localStorage.getItem('merchantTime')
             let curDate = (new Date()).getTime();
             let three = merchantTime * 24 * 3600 * 1000;
             let threeMonths = curDate - three;
             return time.getTime() < threeMonths;
          },
        },
        allTableData: [],
        taskStatusData:[{
          value: 1,
          label: '等待执行'
        },{
          value: 2,
          label: '等待操作'
        },{
          value: 3,
          label: '正在操作'
        },{
          value: 4,
          label: '执行成功'
        },{
          value: 5,
          label: '执行失败'
        },{
          value: 6,
          label: '人工(管理员)终止'
        },{
          value: 7,
          label: '商家终止'
        },{
          value: 8,
          label: '超时失败'
        },{
          value: 9,
          label: '创建中'
        }],
        userToken: window.localStorage.getItem('token')
      }
    },
    created() {
      this.searchForm.token = this.userToken
      this.searchForm.shopType = this.platformType
      this.getCurTime()
      this.getShopList()
      this.getTableData()
    },
    computed:{
      ...mapGetters(['platformType']),
    },
    watch: {
      platformType: function (val) {
        this.searchForm.shopType = val
        this.getTableData()
      }
    },
    methods:{
       dataFilter(val) {
         this.searchForm.shopId = val;
         if (val) { //val存在
           this.shopNameList = this.shopNameOptions.filter((item) => {
             if (!!~item.name.indexOf(val) || !!~item.name.toUpperCase().indexOf(val.toUpperCase())) {
               return true
             }
           })
         } else { //val为空时，还原数组
           this.shopNameList = this.shopNameOptions;
         }
       },
       getShopList() {
         this.$isClick(true);
         apiGetMerchantShopList({
           token: this.userToken
         }).then(res =>{
           this.$isClick(false);
            if (res.code == 1){
             for (var i in res.msg.merchant_shop_list) {
               this.shopNameOptions.push({
                 name: this.platformNameObject[res.msg.merchant_shop_list[i].type] + '-' + res.msg.merchant_shop_list[i].name,
                 id: res.msg.merchant_shop_list[i].id
               })
             }
              this.shopNameList = this.shopNameOptions
            } else {
              this.$message.error(res.msg);
            }
         }).catch(res => {
           this.$isClick(false);
             this.$message.error(res.msg)
         })
       },
       getCurTime() {
         var now = new Date();
         var startTime = new Date(new Date().toLocaleDateString()).getTime() - 24 * 60 * 60 * 1000 * 6
         var endTime = new Date(new Date().toLocaleDateString()).getTime() + 24 * 60 * 60 * 1000 - 1;
         this.searchTime = [startTime,endTime]
         this.searchForm.startTime = Math.floor(startTime / 1000)
         this.searchForm.endTime =  Math.floor(endTime / 1000)
       },
       getTableData(){
         this.$isClick(true);
          apiSaleTaskAllList(this.searchForm).then(res =>{
            this.$isClick(false);
             if (res.code == 1){
              this.tableData = res.msg.res
              this.pageToatal = res.msg.allNum
             } else {
               this.$message.error(res.msg);
             }
          }).catch(res => {
            this.$isClick(false);
              this.$message.error(res.msg)
          })
       },
       getEntranceType(row){
         return this.entranceType[row.entrance_type]
       },
       getShopType(row){
         return this.platformNameObject[row.platform_type]
       },
       searchData(){
         this.searchForm.page = 1
         this.searchForm.pageSize = 10
         this.getTableData()
       },
       resetSearchParam(){
        this.searchForm = {
           token: this.userToken,
           page: 1,
           pageSize: 10,
           shopId: '',
           productId: '',
           planCode: '',
           taskCode: '',
           startTime: '',
           endTime: '',
           shopType: this.platformType
         }
       },
       handleSizeChange(val) {
       	this.searchForm.pageSize = val;
       	this.getTableData()
       },
       handleCurrentChange(val) {
       	this.searchForm.page = val;
       	this.getTableData()
       },
       changeOverTimeType(row) {
         if (row.over_time == 0 || row.over_time == '' || row.over_time == null) {
           return '--'
         }
        if (typeof(row.over_time) != 'number') {
          return row.over_time
        }
         var date = new Date(row.over_time * 1000); //时间戳为10位需*1000，时间戳为13位的话不需乘1000
         return this.getFormatTime(date)
       },
       changeStartTimeType(row) {
         if (typeof(row.begin_time) != 'number') {
           return row.begin_time
         }
         var date = new Date(row.begin_time * 1000); //时间戳为10位需*1000，时间戳为13位的话不需乘1000
        return this.getFormatTime(date)
       },
       getFormatTime (date){
          var Y = date.getFullYear() + '-';
          var M = (date.getMonth() + 1 < 10 ? '0' + (date.getMonth() + 1) : date.getMonth() + 1) + '-';
          var D = (date.getDate() < 10 ? '0' +  date.getDate() : date.getDate()) + ' ';
          var h = (date.getHours() < 10 ? '0' + date.getHours() : date.getHours()) + ':';
          var m = (date.getMinutes() < 10 ? '0' + date.getMinutes() : date.getMinutes()) + ':';
          var s = (date.getSeconds() < 10 ? '0' + date.getSeconds() : date.getSeconds());
          return Y + M + D + h + m + s;
       },
       changeTime(val){
        if (this.searchTime == null) {
          this.searchForm.startTime =  ''
          this.searchForm.endTime =  ''
        } else{
          this.searchForm.startTime =  this.changeTimeType(val[0])
          this.searchForm.endTime =  this.changeTimeType(val[1])
        }
       },
       changeTimeType(time){
         var d = new Date(time);
         var s = d.getFullYear() + '-' + (d.getMonth() + 1) + '-' + d.getDate() + ' ' + d.getHours() + ':' + d.getMinutes() + ':' + d.getSeconds();
         return new Date(s).getTime() /1000;
       },
       toPlanDetailPage(id, item){
         this.$router.push(`/plan/salesPlanDetail?id=${id}&shop_type=${item.platform_type}&status=${item.customize_whether}`);
       },
       getAllTableData(){
         let data = JSON.parse(JSON.stringify(this.searchForm))
         data.page = 1
         data.pageSize = this.pageToatal
         if (data.pageSize == 0) {
            this.$message.error('当前表格没有数据可以导出');
            return
         }
         return new Promise ((resolve) =>{
           this.$isClick(true);
           apiSaleTaskAllList(data).then(res =>{
             this.$isClick(false);
              if (res.code == 1){
                 this.allTableData = res.msg.res
                resolve(res) ;
              } else {
                this.$message.error(res.msg);
              }
           }).catch(res => {
             this.$isClick(false);
               this.$message.error(res.msg)
           })
         })

       },
       downloadExcel(){
         this.$loading.show('下载中')
         var wb = ''
          var xlsxParam = { raw: true }
          this.getAllTableData().then(()=>{
          wb = this.XLSX.utils.table_to_book(document.querySelector('#exportTable'),xlsxParam)
          var wbout = this.XLSX.write(wb, { bookType: 'xlsx', bookSST: true, type: 'array' })
          try {
            this.FileSaver.saveAs(new Blob([wbout], { type: 'application/octet-stream' }),'销量全部订单.xlsx')
          } catch (e) { if (typeof console !== 'undefined') console.log(e, wbout) }
          setTimeout(() => {
            this.$loading.hide()
            this.$message.success('下载完成')
          }, 1000);
          return wbout
         })
       },
      exportSaleTaskAllList() {
        this.searchForm.pageSize = this.pageToatal
        apiExportSaleTaskAllList(this.searchForm).then(res => {
          this.$confirm(
              "数据正在导出，请耐心等待",
              "提示",
              {
                confirmButtonText: "确定",
                cancelButtonText: "取消",
                type: "info"
              }
          ).then(() => {
            // 没有前置机时
            // let blob = new Blob([res]);
            // let a = document.createElement("a");
            // a.download = "商户已完成订单.csv";
            // a.href = window.URL.createObjectURL(blob);
            // a.click();

            // 有前置机时
            let a = document.createElement("a");
            a.href = res.msg;
            a.click();
            this.$message.success("商户全部订单正在导出");
          }).catch(() => {
                this.$message({
                  type: "info",
                  message: "已取消"
                });
              });
        });
      },
    }
  }
</script>

<style lang="less">
  #sales-all-order{

  }
  .el-popover {
    .goods-preview-img,.keyword-preview-img {
      width: 200px;
      height: 200px;
    }
  }
</style>
